//
//  WBWelcomeView.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/9.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

class WBWelcomeView: UIView {
    /// 头像的属性
    lazy var iconView: UIImageView = {
        let imageView = UIImageView()
        
        imageView.wb_setImage(urlStr: WBUserAccount.shared.avatar_large, placeHolderImage: "avatar_default_big")
        
        return imageView
    }()
    
    override func didMoveToWindow() {
        super.didMoveToWindow()

        //4. 添加动画
        addAnimation()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    /// 标题的属性
    lazy var titleLabel: UILabel = UILabel(text: "欢迎归来,\(WBUserAccount.shared.screen_name!)", alignment: .center)

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WBWelcomeView {
    func setupUI () {
        backgroundColor = UIColor.white
        
        //1. 添加子视图
        addSubview(iconView)
        addSubview(titleLabel)
        
        //2. 设置子视图
        //设置圆角头像(cornerRadius设半径)
        iconView.layer.cornerRadius = 45
        iconView.layer.masksToBounds = true
        
        //3. 自动布局
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(150)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.left.equalTo(self).offset(100)
            make.right.equalTo(self).offset(-100)
            make.bottom.equalTo(self).offset(-120)
        }
        
        //手动调用layoutSubViews，让我们设的自动布局生效
        layoutIfNeeded()
    }
    
    /// 添加动画
    func addAnimation() {
        //只是修改了布局的属性的值，但是并没有生效
        self.iconView.snp.updateConstraints { (make) in
            make.top.equalTo(self).offset(100)
        }
        
        /// 动画的参数说明
        ///
        /// - Parameter withDuration: 动画的执行时长
        /// - Parameter delay: 延迟时间
        /// - Parameter usingSpringWithDamping: 弹力系数（0到1）, 越小越弹
        /// - Parameter initialSpringVelocity: 重力系数（地球上9.8）
        UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 9.8, options: [], animations: {
            //该方法一旦调用，就会调用layoutSubViews方法，此时，动画才生效
            self.layoutIfNeeded()
        }) { (_) in
            self.removeFromSuperview()
        }
    }
}
